const jwt = require('jsonwebtoken');
const secretKey = 'itheima No1 ^_^';
 //model 数据层
module.exports = class shoppingModel extends require('./Model') {

    // 获取商品列表
    static getShopList(req, res) {
        return new Promise((resolve, reject) => {
            console.log("req.headers",req.headers)

            const token = req.headers.authorization?.split(' ')[1];
            if (!token) {
                return res.status(401).send({ status: 0, message: 'error', errorMessage: "未提供授权令牌" });
            }

            try {
                const decoded = jwt.verify(token, secretKey);
                const id = decoded.id;
                console.log(id);
                let sql = 'SELECT * FROM shopping WHERE user_id = ?';
                this.query(sql, [id])
                    .then((r) => {
                        resolve(r);
                    })
                    .catch((e) => {
                        reject(e);
                    });
            } catch (e) {
                res.status(401).send({ status: 0, message: 'error', errorMessage: "无效的授权令牌" });
                reject(e);
            }
        });
    }

    // 修改购物车商品数量
    static updateShop(req, res) {
        return new Promise((resolve, reject) => {
            const token = req.headers.authorization?.split(' ')[1];
            if (!token) {
                return res.status(401).send({ status: 0, message: 'error', errorMessage: "未提供授权令牌" });
            }
            try {
                const decoded = jwt.verify(token, secretKey);
                const userId = decoded.id;

                const { goodId, num } = req.body;
                if (!goodId || !num) {
                    return res.status(400).send({ status: 0, message: 'error', errorMessage: "缺少必要参数" });
                }

                let sql = 'UPDATE shopping SET num = ? WHERE user_id = ? AND good_id = ?';
                this.query(sql, [num, userId, goodId])
                    .then((result) => {
                        if (result.affectedRows === 0) {
                            reject({ message: '未找到相关购物车项' });
                        } else {
                            resolve({ message: '更新成功' });
                        }
                    })
                    .catch((error) => {
                        reject(error);
                    });
            } catch (e) {
                res.status(401).send({ status: 0, message: 'error', errorMessage: "无效的授权令牌" });
                reject(e);
            }
        });
    }

    // 删除购物车商品
    static deleteShop(req, res) {
        return new Promise((resolve, reject) => {
            const token = req.headers.authorization?.split(' ')[1];
            if (!token) {
                return res.status(401).send({ status: 0, message: 'error', errorMessage: "未提供授权令牌" });
            }
            try {
                const decoded = jwt.verify(token, secretKey);
                const userId = decoded.id;

                console.log("req.query.id",req.body.id)
                const id  = req.body.id;
                if (!id) {
                    return res.status(400).send({ status: 0, message: 'error', errorMessage: "缺少必要参数" });
                }

                let sql = 'DELETE FROM shopping WHERE id = ?';
                this.query(sql, [id])
                    .then((result) => {
                        if (result.affectedRows === 0) {
                            reject({ message: '未找到相关购物车项' });
                        } else {
                            resolve({ message: '删除成功' });
                        }
                    })
                    .catch((error) => {
                        reject(error);
                    });
            } catch (e) {
                res.status(401).send({ status: 0, message: 'error', errorMessage: "无效的授权令牌" });
                reject(e);
            }
        });
    }
    //增加购物车数据
    static addShop(req, res) {
        return new Promise((resolve, reject) => {
            const token = req.headers.authorization?.split(' ')[1];
            if (!token) {
                return res.status(401).send({ status: 0, message: 'error', errorMessage: "未提供授权令牌" });
            }
            try {
                const decoded = jwt.verify(token, secretKey);
                const id = decoded.id;

                const goodId = req.body.goodId;
                const shoppingItem = {
                    user_id: null,
                    num: 1,
                    good_id: goodId,
                    name: '',
                    price: null,
                    remark: '',
                    cover_img: ''
                };
                shoppingItem.user_id = id;
                let goodSql = 'SELECT * FROM baking_good WHERE id = ?';

                this.query(goodSql, [goodId])
                    .then((goodResult) => {
                        console.log("goodId", goodId)
                        console.log("goodResult", goodResult)
                        if (goodResult.length === 0) {
                            reject({ message: '商品不存在' });
                        } else {
                            shoppingItem.name = goodResult[0].name;
                            shoppingItem.price = goodResult[0].price;
                            shoppingItem.cover_img = goodResult[0].cover_img;
                            shoppingItem.remark = goodResult[0].remark;
                            let sql = 'INSERT INTO shopping SET ?';
                            this.query(sql, [shoppingItem]).then((result) => {
                                resolve({ message: '添加成功' });
                            });
                        }
                    });
            } catch (e) {
                res.status(401).send({ status: 0, message: 'error', errorMessage: "无效的授权令牌" });
                reject(e);
            }
        });
    }
}